package com.pangu.core.engine.game;

import java.util.ArrayList;
import java.util.List;

import org.springframework.stereotype.Service;

import com.corundumstudio.socketio.SocketIOClient;
import com.pangu.core.BMDataContext;
import com.pangu.core.BMDataContext.GameStatusEnum;
import com.pangu.core.BMDataContext.PlayerTypeEnum;
import com.pangu.core.cache.CacheConfigTools;
import com.pangu.core.cache.CacheHelper;
import com.pangu.core.engine.game.model.PlayerRecordDezhou;
import com.pangu.core.engine.game.model.PlayerRecordNiuniu;
import com.pangu.util.GameUtils;
import com.pangu.util.PlayerUtils;
import com.pangu.util.disruptor.DisruptorHandler;
import com.pangu.util.rules.model.TopPlayer;
import com.pangu.web.model.GameBonusPool;
import com.pangu.web.model.GameRoom;
import com.pangu.web.model.PlayUserClient;
import com.pangu.web.model.SysGameConfig;
import com.pangu.web.service.repository.jpa.GameBonusPoolRepository;

import lombok.extern.slf4j.Slf4j;

/**
 * @ClassName: ChessGameEngine
 * @Description: 棋牌游戏引擎，补充以及简化贝密的一些流程,公共调用的方法
 * @author 老王
 * @date 2018年3月24日 下午1:56:35
 *
 */
@Service(value = "chessGameEngine")
@Slf4j
public class ChessGameEngine {

	/**
	 * @Description :发送下注记录到前端,兼容牛牛以及德州
	 * @author 老王
	 * 
	 */
	public void sendRecord(GameRoom gameRoom, String type) {

		List<PlayUserClient> plays = CacheHelper.getGamePlayerCacheBean().getCacheObject(gameRoom.getId(),
				gameRoom.getOrgi());
		if (plays == null) {
			return;
		}

		if (BMDataContext.GameTypeEnum.NIUNIU.toString().equals(type)) {
			for (PlayUserClient playUserClient : plays) {
				List<PlayerRecordNiuniu> record = (List<PlayerRecordNiuniu>) CacheHelper.getGameRecordNiuNiuCacheBean()
						.getCacheObject(playUserClient.getId(), gameRoom.getOrgi());
				if (record == null) {
					continue;
				}
				for (PlayerRecordNiuniu playerRecordNiuniu : record) {
					ActionTaskUtils.sendEvent(playerRecordNiuniu.getCommand(), playerRecordNiuniu, gameRoom);
				}
			}
		}

		if (BMDataContext.GameTypeEnum.DEZHOU.toString().equals(type)) {
			for (PlayUserClient playUserClient : plays) {
				List<PlayerRecordDezhou> record = (List<PlayerRecordDezhou>) CacheHelper.getGameRecordDeZhouCacheBean()
						.getCacheObject(playUserClient.getId(), gameRoom.getOrgi());
				if (record == null) {
					continue;
				}
				for (PlayerRecordDezhou playerRecord : record) {
					ActionTaskUtils.sendEvent(playerRecord.getCommand(), playerRecord, gameRoom);
				}
			}
		}

	}

	/**
	 * @Description :获取座位信息发送到前端
	 */
	public void sendTopPlayer(GameRoom gameRoom, String orgi) {
		TopPlayer toper = (TopPlayer) CacheHelper.getGamePlayerTopCacheBean().getCacheObject(gameRoom.getId(),
				gameRoom.getOrgi());
		if (toper != null) {
			ActionTaskUtils.sendEvent(BMDataContext.BEIMI_GAME_SEAT, toper, gameRoom);
		}
	}

	/**
	 * @Description :获取座位信息发送到前端
	 * 
	 */
	public TopPlayer getTopPlayer(String roomId, String orgi, int i) {
		TopPlayer toper = (TopPlayer) CacheHelper.getGamePlayerTopCacheBean().getCacheObject(roomId, orgi);
		if (toper == null) {
			return null;
		}
		if (100 == i) {
			toper.setCommand(BMDataContext.BEIMI_GAME_TOP);
		} else {
			toper = GameUtils.getToper(toper, i);
			toper.setCommand(BMDataContext.BEIMI_GAME_SEAT);
		}
		return toper;
	}

	/**
	 * @Description :获取座位信息发送到前端
	 * 
	 */
	public void sendTopPlayer(SocketIOClient client, String roomId, String orgi, int i) {
		TopPlayer toper = (TopPlayer) CacheHelper.getGamePlayerTopCacheBean().getCacheObject(roomId, orgi);
		if (toper == null) {
			return;
		}
		if (100 == i) {
			toper.setCommand(BMDataContext.BEIMI_GAME_TOP);
			client.sendEvent(BMDataContext.BEIMI_GAME_TOP, toper);
		} else {
			toper = GameUtils.getToper(toper, i);
			toper.setCommand(BMDataContext.BEIMI_GAME_SEAT);
			client.sendEvent(BMDataContext.BEIMI_GAME_SEAT, toper);
		}

	}

	/**
	 * 更新排行榜数据
	 */
	public TopPlayer updateTop(String roomId, String orgi) {
		List<PlayUserClient> playerList = CacheHelper.getGamePlayerCacheBean().getCacheObject(roomId, orgi);

		if (playerList == null) {
			log.info("更新Top消息为空···············请查原因");
			return null;
		}
		/*
		 * 初始化排行榜数据
		 */
		ArrayList<PlayUserClient> list = new ArrayList<>();
		for (PlayUserClient playUserClient : playerList) {
			if (playUserClient.isBlank()) {
				list.add(playUserClient);
				break;
			}
		}
		list.addAll(PlayerUtils.getTopPlayersByMoney(playerList, 100));
		TopPlayer top = new TopPlayer();
		top.setPlayer(list);
		CacheHelper.getGamePlayerTopCacheBean().put(roomId, top, orgi);
		return top;
	}

	/*
	 * 退出房间,通用方法
	 */
	public void leaveRoom(String roomId, String orgi) {
		SysGameConfig gameConfig = CacheConfigTools.getSysGameConfig(orgi);
		// 获取玩家
		List<PlayUserClient> plays = CacheHelper.getGamePlayerCacheBean().getCacheObject(roomId, orgi);
		for (PlayUserClient playUserClient : plays) {
			PlayUserClient userClient = (PlayUserClient) CacheHelper.getApiUserCacheBean()
					.getCacheObject(playUserClient.getId(), orgi);
			if (!BMDataContext.BEIMI_GAME_AI.equals(playUserClient.getPlayertype())) {
				if (userClient != null && (BMDataContext.PlayerTypeEnum.LEAVE.toString().equals(userClient.getStatus())
						|| BMDataContext.PlayerTypeEnum.OFFLINE.toString().equals(userClient.getStatus()))) {
					log.info("{}退出来房间·················", userClient.getUsername());
					CacheHelper.getGamePlayerCacheBean().delete(userClient.getId(), orgi);
					CacheHelper.getRoomMappingCacheBean().delete(userClient.getId(), orgi);
				}
			} else if (BMDataContext.BEIMI_GAME_AI.equals(playUserClient.getPlayertype()) && userClient != null
					&& (userClient.getGoldcoins() < BMDataContext.GAME_NIUNIU_AI_MIN_COIN)) {// ||
				// FIXME ai退出问题,getAiofflinecoins
				CacheHelper.getGamePlayerCacheBean().delete(userClient.getId(), orgi);
				CacheHelper.getRoomMappingCacheBean().delete(userClient.getId(), orgi);
			}
		}

	}

	/**
	 * 结束 当前牌局，清除牌局相关的数据 清楚下注记录
	 * 
	 * @param orgi
	 * @return
	 */
	public void finished(GameRoom gameRoom, List<PlayUserClient> plays, String play) {
		if (gameRoom != null) {//
			// CacheHelper.getExpireCache().remove(roomid); 房间暂时永远不过期
			CacheHelper.getBoardCacheBean().delete(gameRoom.getId(), gameRoom.getOrgi());// 牌局过期
			if (BMDataContext.GameTypeEnum.NIUNIU.toString().equals(play)) {
				CacheHelper.getGameRecordNiuNiuCacheBean().delete(gameRoom.getId(), gameRoom.getOrgi());// 清除流水记录
				for (PlayUserClient playUserClient : plays) {
					CacheHelper.getGameRecordNiuNiuCacheBean().delete(playUserClient.getId(), gameRoom.getOrgi());
				}
			} else if (BMDataContext.GameTypeEnum.DEZHOU.toString().equals(play)) {
				CacheHelper.getGameRecordDeZhouCacheBean().delete(gameRoom.getId(), gameRoom.getOrgi());// 清除流水记录
				for (PlayUserClient playUserClient : plays) {
					CacheHelper.getGameRecordDeZhouCacheBean().delete(playUserClient.getId(), gameRoom.getOrgi());
				}
			}
			gameRoom.setStatus(GameStatusEnum.READY.toString());
			CacheHelper.getGameRoomCacheBean().put(gameRoom.getId(), gameRoom, gameRoom.getOrgi());
		}

	}

	/**
	 * 检查是否有人
	 */
	public boolean checkHaveMan(String gameId, String orgi) {
		boolean result = false;
		List<PlayUserClient> plays = CacheHelper.getGamePlayerCacheBean().getCacheObject(gameId, orgi);
		if (plays != null && plays.size() > 0) {// 玩家是允许为空的。
			result = true;
		}
		return result;
	}

	/**
	 * 检查是否有真人
	 */
	public boolean checkHaveRealMan(String gameId, String orgi) {
		boolean result = false;
		List<PlayUserClient> plays = CacheHelper.getGamePlayerCacheBean().getCacheObject(gameId, orgi);
		if (plays == null) {// 玩家是允许为空的。
			return result;
		}
		for (PlayUserClient playUserClient : plays) {
			if (PlayerTypeEnum.NORMAL.toString().equals(playUserClient.getPlayertype())) {
				result = true;
				break;
			}
		}
		return result;
	}

	/**
	 * @Description :创建AI,传入这局的要求达到的个数
	 * @author 老王
	 */
	public void createAI(int count, String roomId, String orgi) {
		// 执行生成AI
		List<PlayUserClient> playerList = CacheHelper.getGamePlayerCacheBean().getCacheObject(roomId, orgi);
		int aicount = count - playerList.size();
		if (aicount > 0) {
			for (int i = 0; i < aicount; i++) {
				PlayUserClient playerUser = CacheHelper.getQuenePlayerCache().poll(orgi);
				if (playerUser == null) {
					break;
				}
				playerUser.setPlayerindex(System.currentTimeMillis()); // 按照加入房间的时间排序，有玩家离开后，重新发送玩家信息列表，重新座位
				playerUser.setRoomid(roomId);
				playerUser.setRoomready(true);
				playerUser.setOnline(true);
				CacheHelper.getGamePlayerCacheBean().put(playerUser.getId(), playerUser, orgi); // 将用户加入到 room ，
				playerList.add(playerUser);
			}
		}
		log.info("当前桌人数：{}", playerList.size());
		// 更新 toper
		BMDataContext.getContext().getBean(ChessGameEngine.class).updateTop(roomId, orgi);
	}

	/*
	 * 判断是否作弊
	 */
	public boolean isBeginCheat(String gameType, String orgi) {
		GameBonusPool coin = (GameBonusPool) CacheHelper.getGameBonusPoolCacheBean().getCacheObject(gameType, orgi);
		if (coin.getCoin() < coin.getValve() && GameUtils.getChance(coin.getChance())) {
			return true;
		}
		return false;
	}

	/*
	 * 更新奖金池
	 */
	public void updateGameBonusPool(String gameType, double coin, String orgi) {
		GameBonusPool gbp = (GameBonusPool) CacheHelper.getGameBonusPoolCacheBean().getCacheObject(gameType, orgi);
		gbp.setCoin(gbp.getCoin() + coin);
		CacheHelper.getGameBonusPoolCacheBean().put(gameType, gbp, orgi);
		DisruptorHandler.published(gbp, null, BMDataContext.getContext().getBean(GameBonusPoolRepository.class));
	}

}
